package LC;

/**
 * https://leetcode.com/problems/search-in-rotated-sorted-array-ii/description/
 * Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
 * (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
 * Write a function to determine if a given target is in the array.
 * The array may contain duplicates.
 */
public class LC_081_SearchinRotatedSortedArrayII_Array_TwoPointers_BinarySearch {
    public static void main(String[] args) {
        int[] a = new int[]{0, 1, 2, 3, 4, 5, 6, 7, 8};
        int target = 5;
        boolean f = Solution.search(a, target);
        System.out.println(f);
    }

    static class Solution {
        static boolean search(int[] nums, int target) {
            int left = 0;
            int right = nums.length - 1;
            while (left <= right) {
                int mid = (left + right) / 2;
                if (nums[mid] == target)
                    return true;
                if (nums[left] < nums[mid]) {
                    if (nums[left] <= target && target < nums[mid])
                        right = mid - 1;
                    else
                        left = mid + 1;
                } else if (nums[left] > nums[mid]) {
                    if (nums[mid] < target && target <= nums[right])
                        left = mid + 1;
                    else
                        right = mid - 1;
                } else
                    left++;
            }
            return false;
        }
    }
}
